
class Interval {
    start: number;
    end: number;
    static fromArray(xs: number[][]): Interval[] { 
        return xs.map(xs => ({ start: xs[0], end: xs[1]}));
    }
    static toArray (xs: Interval[]) { 
        return xs.map((x => [x.start, x.end]))
    }
}

function merge(intervals: Interval[]): number[][] {
    intervals.sort((x, y) => x.start - y.start)
    if (intervals.length < 2) return intervals.map(x => [ x.start, x.end ]);
    var left = 0, right = 1;
    while(right < intervals.length) {
        if(intervals[right].start <= intervals[left].end) {
            var start = Math.min(intervals[left].start, intervals[right].start);
            var end = Math.max(intervals[left].end, intervals[right].end);
            intervals.splice(left, 2, { start: start, end: end });
        }
        else {
            left++;
            right++;
        }
    }
    return intervals.map(x => [ x.start, x.end ]);
}

let input56 = Interval.fromArray([[1,3],[2,6],[8,10],[15,18]]);
let output56 = merge( input56);

output56 = merge( Interval.fromArray([[1,4],[1,6]]));

output56 = merge( Interval.fromArray([[1,4],[0,4]]));

output56 = merge( Interval.fromArray([[1,4],[0,0]]));

console.log( 'The End');